package com.zcyr.util;

import com.zcyr.constant.Constants;
import com.zcyr.pojo.SQLResult;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

public class StatementTool {

    /**
     * 获取stmt的最后一个执行结果
     *
     * @param stmt statement对象
     * @return 如果获取失败，则返回空
     */
    public static HashMap<String, Object> getLastResult(Statement stmt) throws SQLException {
        ArrayList<HashMap<String, Object>> allNotClosedResults = new ArrayList<>();
        do{
            HashMap<String, Object> result = new HashMap<>();
            result.put("resultSet", stmt.getResultSet());
            result.put("updateCount", stmt.getUpdateCount());
            allNotClosedResults.add(result);
        }while (!(!stmt.getMoreResults(Statement.KEEP_CURRENT_RESULT) && stmt.getUpdateCount() == -1));

        int size = allNotClosedResults.size();
        for(int i=0; i<size-1; i++){
            ResultSet rs =  (ResultSet) allNotClosedResults.get(i).get("resultSet");
            if (rs != null){ rs.close();}
        }
        return allNotClosedResults.get(size - 1);
    }

    public static SQLResult getResult(Statement stmt) throws SQLException {
        int count = stmt.getUpdateCount();
        try(ResultSet rs = stmt.getResultSet()){
            if (count != -1){
                return new SQLResult(
                        count,
                        null,
                        null,
                        Constants.TYPE_SQL_RESULT_UPDATE);
            } else if (rs != null){
                return new SQLResult(
                        -1,
                        ResultSetTool.getMetaData(rs.getMetaData()),
                        ResultSetTool.getAllData(rs),
                        Constants.TYPE_SQL_RESULT_QUERY);
            } else {
                return new SQLResult(
                        count,
                        null,
                        null,
                        Constants.TYPE_SQL_RESULT_UNKNOWN);
            }
        }
    }
}
